<template>
  <view class="shop-check">
    <up-popup :show="show" :closeable="true" @close="onClose">
      <view class="px-20">
        <view class="flex justify-start mt-100">
          <image class="shop-img mr-28" :src="specifList[current].sizelist.skuPic.split(',')[0]" v-if="specifList[current].sizelist.skuPic" />
          <view class="flex column">
            <view class="price f-40-B">￥{{ specifList[current].price }}</view>
          </view>
        </view>
        <view class="mt-32 f-32">颜色</view>
        <view class="flex flex-wrap">
          <view class="specif-item mt-16 mr-16 tc f-28" :class="{ 'active': item.checked, 'disabled': item.count == 0 }"
            v-for="(item, index) in specifList" :key="index" @click="onCheckSpecif(item, index)">
            {{ item.name }}
          </view>
        </view>
        <view class="mt-32 f-32">尺码</view>
        <view class="flex justify-between flex-wrap items-center mt-64" style="max-height: 270px;overflow: scroll;" >
          <view class="size-item" v-for="(item,index) in specifList[current].sizelist" :key="index">
            <view class="f-32">
              <view>{{ item.size }}</view>
              <view class="f-24 colorgray" :class="{ 'stock': item.stock == 0 }">{{item.status}}</view>
            </view>
            <view>
              <view class="flex mb-12">
                <text class="input cart-reduce" @click="onMinus1(item,index)">-</text>
                <text class="input cart-text">{{ item.num }}</text>
                <text class="input cart-add" @click="onAdd1(item,index)">+</text>
              </view>
            </view>
          </view>
        </view>
        <view class="confirm-btn my-32 tc f-28-B"
          :class="{ 'pay-active': props.specType == 2, 'pay-disabled': specifList[current].stock == 0 }"
          @click="props.specType == 1 ? onCart() : onPay()">
          {{ props.specType == 1 ? "确定" : "立即购买" }}
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const emit = defineEmits(["close", "cart", "pay"]);
const props = defineProps({
  showType: {
    type: Number,
    default: 1
  },
  specifList: {
    type: Array,
    default: () => []
  },
  specType: {
    type: Number,
    default: 1
  }
});

// 深拷贝 specifList，避免直接修改 props
const specifList = ref(JSON.parse(JSON.stringify(props.specifList)));
const current = ref(0); // 当前选中的颜色索引
const show = ref(true); // 控制弹窗显示

// 如果 specifList 不为空，初始化第一个颜色为选中状态
if (specifList.value.length) {
  specifList.value[0].checked = true;
}
// 减少数量
const onMinus1 = (item, index) => {
  if (specifList.value[current.value].sizelist[index].num > 0) {
    specifList.value[current.value].sizelist[index].num--;
  } else {
    uni.showToast({
      title: "数量不能小于0",
      icon: "none"
    });
  }
  getSumTotal();
};

// 增加数量
const onAdd1 = (item, index) => {
  if (specifList.value[current.value].sizelist[index].num < item.inventory) {
    specifList.value[current.value].sizelist[index].num++;
  } else {
    uni.showToast({
      title: "已达到最大库存",
      icon: "none"
    });
  }
  getSumTotal();
};

// 计算总价（如果需要）
const getSumTotal = () => {
  // 占位符，用于总价计算逻辑
};

// 选择颜色
const onCheckSpecif = (item, index) => {
  if (item.stock == 0) return; // 无库存时不可选
  current.value = index;
  specifList.value.forEach((spec) => {
    spec.checked = false; // 取消其他颜色的选中
  });
  item.checked = true; // 设置当前颜色为选中
};

// 关闭弹窗
const onClose = () => {
  emit("close");
};

// 验证选择是否有效
const isValidSelection = () => {
  const currentItem = specifList.value[current.value];
  const hasSizeSelected = currentItem.sizelist.some(item => item.num > 0); // 是否选择了尺码
  const hasColorSelected = currentItem.checked; // 是否选择了颜色
  return hasColorSelected && hasSizeSelected;
};

// 加入购物车
const onCart = () => {
  if (specifList.value[current.value].stock == 0) {
    uni.showToast({
      title: "该商品库存不足，无法加入购物车",
      icon: "none",
      mask: true
    });
    return;
  }
  if (!isValidSelection()) {
    uni.showToast({
      title: "请选择颜色和尺码",
      icon: "none",
      mask: true
    });
    return;
  }
  emit("cart", specifList.value); // 触发加入购物车事件
};

// 立即购买
const onPay = () => {
  if (specifList.value[current.value].stock == 0) {
    uni.showToast({
      title: "该商品库存不足，无法购买",
      icon: "none",
      mask: true
    });
    return;
  }
  if (!isValidSelection()) {
    uni.showToast({
      title: "请选择颜色和尺码",
      icon: "none",
      mask: true
    });
    return;
  }
  emit("pay", specifList.value[current.value]); // 触发立即购买事件
};
</script>

<style lang="scss" scoped>
.shop-check {
  .shop-img {
    width: 200rpx;
    height: 200rpx;
    border-radius: 16rpx;
  }

  .price {
    color: #F53F3F;
  }

  .specif-item {
    width: 218rpx;
    height: 64rpx;
    line-height: 64rpx;
    background: #F5F5F5;
    border-radius: 32rpx;
  }

  .specif-item:nth-child(3n) {
    margin-right: 0;
  }

  .active {
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
  }

  .disabled {
    background: #F5F5F5;
    color: #909193;
  }

  .input {
    display: block;
    width: 44rpx;
    height: 44rpx;
    line-height: 44rpx;
    text-align: center;
    float: left;
  }

  .cart-add {
    border-left: none;
    border: 2rpx solid #ededed;
    border-radius: 0rpx 8rpx 8rpx 0rpx;
    font-size: 36rpx;
    color: #CCCCCC
  }

  .cart-reduce {
    border-right: none;
    border: 2rpx solid #ededed;
    border-radius: 8rpx 0rpx 0rpx 8rpx;
    font-size: 36rpx;
    color: #CCCCCC
  }

  .cart-text {
    width: 44rpx;
    border-top: 2rpx solid #ededed;
    border-bottom: 2rpx solid #ededed;
    font-size: 28rpx;
  }

  .cart-tip {
    color: #606266;
  }

  .confirm-btn {
    width: 100%;
    height: 72rpx;
    line-height: 72rpx;
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
    border-radius: 104rpx;
  }

  .pay-active {
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
  }

  .pay-disabled {
    background: #909193;
    color: #ffffff;
  }

  :deep(.u-icon__icon) {
    color: #000000 !important;
    font-size: 30rpx !important;
  }

  .size-item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;
    .colorgray {
      color: #909193;
    }
  }
}
</style>